package client;

import static debug.Debug.DBUG;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AlfaListener implements Runnable {
		private BufferedReader in;
		private ServerConnection server;
		private Map<String, List<AlfaHandeler>> listeners;
		
		public AlfaListener(ServerConnection sc) {
			this.server = sc;
			listeners = new HashMap<String, List<AlfaHandeler>>();
		}
		
		public void addAlfaHandeler(String s, AlfaHandeler a) {
			if (!listeners.containsKey(s)) {
				listeners.put(s, new ArrayList<AlfaHandeler>());
			}
			listeners.get(s).add(a);
		}
		
		@Override
		public void run() {
			String inline;
			String[] parts;
			while (true) {
				try {
					inline = in.readLine();
					if (!inline.startsWith("unit")) {
						DBUG("> "+ inline);
					}
				} catch (IOException e) {
					DBUG("FAILED TO READ");
					server.close();
					return;
				}
				parts = inline.split(" ");
				if (listeners.containsKey(parts[0])) {
					for (AlfaHandeler a: listeners.get(parts[0])) {
						a.alfaUpdate(parts);
					}
				}
			}
		}

		public void setInstream(BufferedReader in) {
			this.in = in;
		}
		
	}
